package io.kiki.task.client.common.rpc.client;

import cn.hutool.core.util.StrUtil;
import io.kiki.task.client.common.config.Properties;
import io.kiki.task.common.core.context.SpringContext;
import io.kiki.task.common.core.util.NetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;

import java.util.Objects;
import java.util.Optional;


@Slf4j
public class NettyChannel {

    private static final int PORT;
    private static final String HOST;


    static {
        PORT = Integer.parseInt(System.getProperty(Properties.CLIENT_PORT, String.valueOf(1789)));
        HOST = System.getProperty(Properties.CLIENT_HOST, NetUtil.getLocalIpStr());
    }

    private NettyChannel() {
    }

    /**
     * 获取服务端端口
     *
     * @return port
     */
    public static int getServerPort() {
        Properties properties = SpringContext.getContext().getBean(Properties.class);
        Properties.ServerConfig serverConfig = properties.getServerConfig();

        String port = System.getProperty(Properties.SERVER_PORT);
        if (StrUtil.isBlank(port)) {
            System.setProperty(Properties.SERVER_PORT, String.valueOf(serverConfig.getPort()));
        }

        return Integer.parseInt(System.getProperty(Properties.SERVER_PORT));
    }

    /**
     * 获取服务端host
     *
     * @return host
     */
    public static String getServerHost() {
        Properties properties = SpringContext.getBean(Properties.class);
        Properties.ServerConfig serverConfig = properties.getServerConfig();

        String host = System.getProperty(Properties.SERVER_HOST);
        if (StrUtil.isBlank(host)) {
            System.setProperty(Properties.SERVER_HOST, serverConfig.getHost());
        }

        return System.getProperty(Properties.SERVER_HOST);
    }

    /**
     * 获取指定的客户IP
     */
    public static String getClientHost() {
        Properties properties = SpringContext.getBean(Properties.class);

        String host = properties.getHost();
        // 获取客户端指定的IP地址
        if (StrUtil.isBlank(host)) {
            host = HOST;
        }

        return host;
    }

    /**
     * 获取客户端端口
     *
     * @return port 端口
     */
    public static Integer getClientPort() {
        Properties properties = SpringContext.getBean(Properties.class);
        ServerProperties serverProperties = SpringContext.getBean(ServerProperties.class);

        Integer port = properties.getPort();
        // 获取客户端指定的端口
        if (Objects.isNull(port)) {
            port = Optional.ofNullable(serverProperties.getPort()).orElse(PORT);
        }

        return port;
    }


}
